<!-- 地图拾取经纬度 -->
<template>
  <div class="map-address">
    <el-form
      :model="longitudeForm"
      :rules="longitudeRules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-row :gutter="20">
        <el-col :span="14">
          <el-form-item label="地址" style="position: relative">
            <el-select
              v-model="address"
              @change="selectOneAddr"
              :remote-method="searchWithName"
              style="width: 100%"
              filterable
              remote
              placeholder="请输入关键词搜索"
            >
              <el-option
                v-for="(item, inx) in addressList"
                :key="inx"
                :label="item.name"
                :value="item.name"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="14">
          <el-form-item label="经纬度">
            <span>{{ longitudeFormValue }}</span>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="mapBox">
      <div id="mapDiv" style="width: 100%; height: 525px"></div>
      <div class="input-card" style="width: auto">
        <div class="input-item">
          <button @click="addLayer" class="btn" style="margin-right: 10px">
            显示卫星图
          </button>
          <button @click="rmLayer" class="btn">隐藏卫星图</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      // lng: 0,
      // lat: 0,
      address: "",
      marker: {},
      input: "",
      map: {},
      addressList: [],
      longitudeRules: {},
      longitudeForm: {
        // 经度
        longitude: 0,
        // 纬度
        latitude: 0,
        address: "",
        localsearch: "",
      },
      placeSearch: "",
      infoWindow: "",
      geocoder: "",
      satellite: "",
    };
  },
  computed: {
    longitudeFormValue() {
      if (this.lng && this.lat) {
        return this.lng + "," + this.lat;
      } else {
        return "";
      }
    },
  },
  props: {
    lat: {
      // type: Number,
      default: 0,
    },
    lng: {
      // type: Number,
      default: 0,
    },
  },
  watch: {
    lng: {
      handler(val) {
        if (val) {
          console.log("进入");
          this.$nextTick(() => {
            this.initMap();
          });
          // this.$nextTick(() => {
          //   this.map = new AMap.Map("mapDiv", {
          //     resizeEnable: true,
          //     center: ['119.028296', '31.651125'],
          //     zoom: 16,
          //   });
          // });
        }
      },
      immediate: true,
    },
    input(val) {
      if (!val) {
        this.addressList = [];
        // 用来清空删除太快时候出现列表的bug

        setTimeout(() => {
          this.addressList = [];
        }, 3000);
      }
    },
  },
  methods: {
    confirm() {
      if (this.lng && this.lat && this.address) {
        this.$emit("closeMapaddressDialog", false);
      } else {
        this.$message.warning("鼠标点选或搜索选中地址后再进行确认");
      }
    },
    // 搜索 天地图LocalSearch
    searchWithName(query) {
      let _this = this;
      if (query) {
        console.log(query);
        _this.map.clearMap();
        _this.placeSearch.search(query, (complete, res) => {
          console.log(res.poiList.pois);
          _this.addressList = res.poiList.pois;
        });
        // _this.localsearch.search(query,4)
      } else {
        _this.addressList = [];
      }
    },
    //解析建议词信息
    suggests(obj) {
      if (obj && obj.length) {
        //建议词提示，如果搜索类型为公交规划建议词或公交站搜索时，返回结果为公交信息的建议词。
        this.addressList = obj;
      }
    },
    //清空地图及搜索列表
    clearAll() {
      this.map.clearOverLays();
    },
    isValidTianDiTuLongitude(longitude) {
      const regex = /^-?\d{1,3}(\.\d+)?$/;
      return regex.test(longitude);
    },
    isValidTianDiTuLatitude(latitude) {
      const regex = /^-?\d{1,2}(\.\d+)?$/;
      return regex.test(latitude);
    },
    selectInit(_lng, _lat) {
      let _this = this;
      if (_lat && _lng) {
        this.lng = _lng;
        this.lat = _lat;
        // 设置左边图标及其大小
        var marker = new AMap.Marker({
          // icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
          icon: new AMap.Icon({
            image:
              "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            size: new AMap.Size(22, 28), //图标所处区域大小
            imageSize: new AMap.Size(22, 28), //图标大小
          }),
          position: [_lng, _lat],
          offset: new AMap.Pixel(-13, -20),
        });

        marker.setMap(this.map);
      } else {
        _lng = 119.028296;
        _lat = 31.651125;
      }
      _this.map = new AMap.Map("mapDiv", {
        resizeEnable: true,
        center: [_lng, _lat],
        zoom: 16,
      });
    },
    destroyMap() {
      if (this.map) {
        this.map.destroy();
      }
    },
    // 初始化地图
    initMap() {
      let _this = this
      if (this.lat && this.lng) {
        console.log("没进来么");
        _this.map = new AMap.Map(document.getElementById("mapDiv"), {
          resizeEnable: true,
          center: [this.lng, this.lat],
          zoom: 16,
        });
        console.log("没进来么", this.lng, this.lat);

        // 设置左边图标及其大小
        var marker = new AMap.Marker({
          icon: new AMap.Icon({
            image:
              "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
            size: new AMap.Size(22, 28), //图标所处区域大小
            imageSize: new AMap.Size(22, 28), //图标大小
          }),
          position: [this.lng, this.lat],
          offset: new AMap.Pixel(-13, -20),
        });

        marker.setMap(this.map);
      } else {
        this.lng = 119.028296;
        this.lat = 31.651125;
        _this.map = new AMap.Map("mapDiv", {
          resizeEnable: true,
          center: [this.lng, this.lat],
          zoom: 16,
        });
      }

      // 设置经纬度转为地址范围
      this.geocoder = new AMap.Geocoder({
        city: "320117", //城市设为北京，默认：“全国”
        radius: 3000, //范围，默认：500
      });
      AMap.plugin(["AMap.PlaceSearch"], function () {
        //构造地点查询类
        _this.placeSearch = new AMap.PlaceSearch({
          // type: '餐饮服务', // 兴趣点类别
          pageSize: 10, // 单页显示结果条数
          pageIndex: 1, // 页码
          city: "320117", // 兴趣点城市
          citylimit: true, //是否强制限制在设置的城市内搜索
          map: _this.map, // 展现结果的地图实例
          autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
        });
      });
      // 设置选中点详情图标
      this.infoWindow = new AMap.InfoWindow({
        autoMove: true,
        offset: { x: 0, y: -30 },
      });

      this.map.on("click", function (e) {
        let lnglat = e.lnglat;
        this.regeoCode(lnglat);
      });
      // 添加卫星图
      this.satellite = new AMap.TileLayer.Satellite();
    },
    regeoCode(_lnglat) {
      let _this = this;
      _this.map.clearMap();
      _this.geocoder.getAddress(_lnglat, function (status, result) {
        if (status === "complete" && result.regeocode) {
          _this.address = result.regeocode.formattedAddress;
          var marker = new AMap.Marker({
            map: _this.map,
            position: _lnglat,
          });
          _this.infoWindow.setContent(
            _this.createContent({
              name: _this.address,
            })
          );
          _this.map.setCenter(marker.getPosition());
          _this.infoWindow.open(_this.map, marker.getPosition());
          _this.lat = _lnglat.lat;
          _this.lng = _lnglat.lng;
        } else {
          _this.$message.warning("根据经纬度查询地址失败");
        }
      });
    },
    selectOneAddr(val) {
      let _obj = this.addressList.find((_v) => _v.name == val);
      if (_obj.id) {
        //添加marker
        var marker = new AMap.Marker({
          map: this.map,
          position: _obj.location,
        });
        this.lat = _obj.location.lat;
        this.lng = _obj.location.lng;
        this.address = _obj.name;
        this.map.setCenter(marker.getPosition());
        this.infoWindow.setContent(this.createContent(_obj));
        this.infoWindow.open(this.map, marker.getPosition());
      } else {
        this.$message.warning("定位出错请重新选择");
      }
    },
    createContent(poi) {
      //信息窗体内容
      var s = [];
      if (poi.name) {
        s.push("<b>名称：" + poi.name + "</b>");
      }
      if (poi.address) {
        s.push("地址：" + poi.address);
      }
      if (poi.tel) {
        s.push("电话：" + poi.tel);
      }
      if (poi.type) {
        s.push("类型：" + poi.type);
      }
      return s.join("<br>");
    },
    //绑定按钮事件
    addLayer() {
      this.map.addLayer(this.satellite);
    },
    rmLayer() {
      this.map.removeLayer(this.satellite);
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initMap();
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy();
    }
  },
};
</script>
<style scoped>
.cur {
  cursor: pointer;
}

.map-address {
  height: auto;
}
.mapBox {
  width: 100%;
  height: auto;
  position: relative;
}
.input-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 0.25rem;
  width: 22rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  position: absolute;
  bottom: 1rem;
  right: 1rem;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 0.75rem 1.25rem;
}
.input-item {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -ms-flex-align: center;
  align-items: center;
  width: 100%;
  height: 3rem;
}
.btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  padding: 0.25rem 0.5rem;
  line-height: 1.5;
  border-radius: 1rem;
  -webkit-appearance: button;
  cursor: pointer;
}
.btn:hover {
  color: #fff;
  background-color: #25a5f7;
  border-color: #25a5f7;
}
#mapDiv {
  height: 100%;
  position: relative;
}

.left-top {
  position: absolute;
  left: 55px;
  top: 120px;
  display: flex;
  flex-direction: column;
}

.address-search {
  width: 20vw;
  z-index: 10000;
  margin-bottom: 20px;
}

.address-list {
  display: flex;
  flex-direction: column;
  z-index: 10000;
  background-color: #fff;
  padding: 10px;
  min-width: 18vw;
  border: 1px solid #dcdfe6;
  position: absolute;
  top: 36px;
  right: 99px;
}
.address-list > div {
  display: flex;
  align-items: center;
  height: 30px;
  cursor: pointer;
  color: #409eff;
}
.address-list > div:hover {
  background-color: #eee;
}
>>> .tdt-control-copyright {
  display: none;
}
>>> .amap-logo,
>>> .amap-copyright {
  display: none !important;
}
</style>
<style>
.address-search .el-input-group__append,
.el-input-group__prepend {
  background-color: #409eff;
  color: #fff;
}
</style>

<style lang="scss">
.demo-ruleForm {
  .el-form-item {
    display: flex;
    line-height: 20px;
  }
}
</style>